package com.hqm.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.hqm.meta.PictureUploadMsg;

/**
 * 图片服务器使用fastdfs作为存储系统，nginx配置反向代理
 * @author hqm2zxy
 *
 */
@Service
public class PictureServiceImpl implements PictureService {
	//图片服务器IP 
	private final String IMAGE_SERVER_BASE_URL = "http://106.2.61.53";
	
	private static final Log logger = LogFactory.getLog(PictureServiceImpl.class);
	
	//图片上传至fastdfd前的参数初始化
	public StorageClient uploadInit() throws 
			FileNotFoundException, IOException, MyException {

//		ClientGlobal.init("/home/hqm2zxy/Desktop/conf/fdfs_client.conf");
		ClientGlobal.init("/home/conf/fdfs_client.conf");
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		StorageServer storageServer = null;
		StorageClient storageClient = new StorageClient(trackerServer, storageServer);
		logger.info("fdfs init");
		return storageClient;
	}
	
	/**
	 * 通过本地图片上传图片
	 * 使用lib中fastdfs_client.jar提供的StorageClient上传
	 */
	@Override
	public PictureUploadMsg uploadPic(MultipartFile picFile) {
		logger.info("uploadPic called");
		PictureUploadMsg result = new PictureUploadMsg();
		//判断图片是否为空
		if (picFile.isEmpty()) {
			result.setError(true);
			result.setMessage("图片为空");
			result.setUrl("");
			return result;
		}
		//上传图片到服务器
		try {
			//取图片名
			String originalFileName = picFile.getOriginalFilename();
			//取图片扩展名
			String extName = originalFileName.substring(originalFileName.indexOf(".")+1);
			StorageClient storageClient = uploadInit();
			String[] strings = storageClient.upload_file(picFile.getBytes(), extName, null);
			
			result.setError(false);
			result.setMessage("图片上传成功");
			//拼接图片url
			StringBuffer url = new StringBuffer(IMAGE_SERVER_BASE_URL);
			for (String string : strings) {
				url.append("/" + string);
			}
			result.setUrl(url.toString());
		} catch (Exception e) {
			result.setError(true);
			result.setMessage("图片上传失败");
			result.setUrl("");
		}
		
		return result;
	}
	
	/**
	 * 通过图片url地址上传图片
	 */
	@Override
	public PictureUploadMsg uploadPic(String picUrl) {
		File image = downloadPic(picUrl);
		PictureUploadMsg result = uploadPic((MultipartFile)image);
		if (image.exists()) {
			image.delete();
		}
		
		return result;
	}

	/**
	 * 下载指定url路径上的图片至工程内作为缓存
	 */
	@Override
	public File downloadPic(String url) {
		String extName = url.substring(url.indexOf("."));
		File imageCache = new File("src/main/webapp/resources/image/cache" + extName);
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		HttpURLConnection httpUrl = null;
		URL imageurl = null;
		int size = 0;
		int BUFFER_SIZE = 1024;
		byte[] buf = new byte[BUFFER_SIZE];
		
		try {
			imageurl = new URL(url);
			httpUrl = (HttpURLConnection) imageurl.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(imageCache);
			while((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.flush();
			fos.close();
			bis.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		httpUrl.disconnect();
		
		return imageCache;
	}

}
